import { useUserStore } from "@/stores/user";
import axios from "axios";
import router from "@/router";
import { ElMessage } from "element-plus";

const baseURL = "http://8.130.47.83:8090";

const instance = axios.create({
  baseURL,
  timeout: 100000,
  headers: { "Content-Type": "application/json" },
});

instance.interceptors.request.use(
  (config) => {
    // const userStore = useUserStore()
    // if (userStore.token) {
    //   config.headers.Authorization = userStore.token
    // }
    const authorization = Cookies.get("authorization");
    if (authorization) {
      config.headers.Authorization = authorization; // 注意：部分后端要求头名称为 "Authorization"（首字母大写），需与后端确认
    }
    return config;
  },
  (err) => Promise.reject(err)
);

instance.interceptors.response.use(
  (res) => {
    if (res.data.code === 200) {
      return res;
    }
    ElMessage({ message: res.data.message || "服务异常", type: "error" });
    return Promise.reject(res.data);
  },
  (err) => {
    ElMessage({
      message: err.response.data.message || "服务异常",
      type: "error",
    });
    console.log(err);
    if (err.response?.status === 401) {
      router.push("/login");
    }
    return Promise.reject(err);
  }
);

export default instance;
export { baseURL };
